package com.hs.android.fortress.intro;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.hs.android.fortress.GameApplication;
import com.hs.android.fortress.R;
import com.hs.android.fortress.ingame.GameScreenActivity;
import com.hs.android.fortress.intro.RoomGetter.Listener;
import com.hs.android.fortress.model.Player;
import com.hs.android.fortress.model.Room;
import com.hs.android.fortress.model.RoomInformation;
import com.hs.android.fortress.net.AsyncNetworking;
import com.hs.android.fortress.net.AsyncNetworking.onNetworkProcessListener;
import com.hs.android.fortress.net.FormPostCommand;
import com.hs.android.fortress.net.NetworkCommand;
import com.hs.android.fortress.net.ParamsMaker;

public class WaitingRoomFragment extends Fragment {
	private static final String TAG = WaitingRoomFragment.class.getSimpleName();
	public static final String EXTRA_ROOM_NUMBER = "com.hs.android.fortress.intro.room_number";

	private GameApplication app;
	
	private View fragmentUi;
	private int roomId;
	private Room mRoom;

	private TextView txtId, txtRoomName;
	private TextView txtP1Id, txtP2Id, txtP3Id, txtP1Status, txtP2Status,
			txtP3Status;

	// Spinner 
	private Spinner spnTank;
	private String[] tanks = { "HS Tank", "CJ Tank", "SJ Tank" };
	private TextView txtWindDir, txtWindSpd;
	
	private Button btnStartGame;

	private String mUserId;
	
	private Timer mTimer;
	private RoomGetter mRoomGetter;
	
	private NetworkCommand mStartGameCommand;
	
	private NetworkCommand mEnterRoomCommand;
	private RoomDialogFactory mFactory;

	public static WaitingRoomFragment newInstance(int roomNumber) {
		Bundle bundle = new Bundle();
		bundle.putInt(EXTRA_ROOM_NUMBER, roomNumber);

		WaitingRoomFragment fragment = new WaitingRoomFragment();
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		roomId = getArguments().getInt(EXTRA_ROOM_NUMBER);
		
		app = (GameApplication) getActivity().getApplication();

		mUserId = app.getUserId();
		
		mStartGameCommand = new FormPostCommand("/gamecontroller/start", ParamsMaker.makeRoomNumberParam(roomId));
		
		mEnterRoomCommand = new FormPostCommand("/room/enter", ParamsMaker.makeIdNumberParams(mUserId, roomId));
		mFactory = new RoomDialogFactory(getActivity());
		
		mRoomGetter = new RoomGetter(new Handler());
		mRoomGetter.setListener(new Listener() {
			
			@Override
			public void onRoomInformationGotten(Room room) {
				mRoom = room;
				
				if(room.getRoomState() == RoomInformation.STATE_PLAYING){
					for(Player player : mRoom.getPlayerList()){
//						Log.d(TAG,"Player id : " + player.getId());
						if(mUserId.equals(player.getId())){
							app.setMyPlayer(player);
							break;
						}
					}
					
					Intent i = new Intent(getActivity(),GameScreenActivity.class);
					i.putExtra(GameScreenActivity.EXTRA_ROOM_NUMBER, roomId);
					startActivity(i);
					getActivity().finish();
					
				}else if(room.getRoomState() == RoomInformation.STATE_WAITING){
					clear();
					
					if(room.getPlayerNumber() > 0){
						setUI(room);
					}
				}
			}
		});
		mRoomGetter.start();
		mRoomGetter.getLooper();
	}

	@Override
	public void onResume() {
		super.onResume();
		
		TimerTask task = new TimerTask() {
			
			@Override
			public void run() {
				mRoomGetter.queueRoomNumber(roomId);
			}
		};
		
		mTimer = new Timer();
		mTimer.schedule(task, 3000, 1000);
		
		
		AsyncNetworking.newInstance(getActivity(), mEnterRoomCommand, mListener).execute();

	}

	@Override
	public void onPause() {
		super.onPause();
//		getActivity().unregisterReceiver(receiver);
		
		if(mTimer != null){
			mTimer.cancel();
			mTimer.purge();
			mTimer = null;
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		mRoomGetter.quit();
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mRoomGetter.clearQueue();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		fragmentUi = inflater.inflate(R.layout.fragment_waiting_room,
				container, false);

		txtId = (TextView) fragmentUi.findViewById(R.id.txt_id_wr);
		txtRoomName = (TextView) fragmentUi.findViewById(R.id.txt_room_name);
		txtP1Id = (TextView) fragmentUi.findViewById(R.id.txt_p1_id);
		txtP2Id = (TextView) fragmentUi.findViewById(R.id.txt_p2_id);
		txtP3Id = (TextView) fragmentUi.findViewById(R.id.txt_p3_id);
		txtP1Status = (TextView) fragmentUi.findViewById(R.id.txt_p1_status);
		txtP2Status = (TextView) fragmentUi.findViewById(R.id.txt_p2_status);
		txtP3Status = (TextView) fragmentUi.findViewById(R.id.txt_p3_status);
		btnStartGame = (Button) fragmentUi.findViewById(R.id.btn_startgame);
		btnStartGame.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				AsyncNetworking.newInstance(getActivity(), mStartGameCommand, mListener).execute();
			}
		});

		spnTank = (Spinner) fragmentUi.findViewById(R.id.spn_tank);
		txtWindDir = (TextView)fragmentUi.findViewById(R.id.txt_wind_dir);
		txtWindSpd = (TextView)fragmentUi.findViewById(R.id.txt_wind_speed);
		
		ArrayAdapter adapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_spinner_item, tanks);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnTank.setAdapter(adapter);
		spnTank.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				AsyncNetworking.newInstance(getActivity(), new FormPostCommand("/playersetting/tank", ParamsMaker.makeSetTankParams(mUserId, position+1)), 
						new onNetworkProcessListener() {
							
							@Override
							public void onPostExecute(String result) {
								if(result == null){
									AsyncNetworking.makeNetworkProblemDialog(getActivity()).setPositiveButton("OK", null).create().show();
								}
							}
						}).execute();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
			
		});
		return fragmentUi;
	}

	private void setUI(Room room) {
		txtRoomName.setText(room.getRoomName());
		
		List<Player> players = room.getPlayerList();
		
		Player p = null;
		
		if (players.get(0).equals(app.getPlayer()) && players.size() > 1) {
			btnStartGame.setEnabled(true);
			btnStartGame.setVisibility(Button.VISIBLE);
		} else {
			btnStartGame.setEnabled(false);
			btnStartGame.setVisibility(Button.INVISIBLE);
		}

		txtId.setText("" + roomId);
		
		StringBuilder sb = new StringBuilder();

		sb = new StringBuilder("Win/Lose (%): ");

		switch (players.size()) {
		case 3:
			p = players.get(2);
			txtP3Id.setText(p.getId());
			sb.append(p.getWin() + " / " + p.getLose() + " (" + (int)p.calculateWinRate()
					+ ")\n");
			sb.append("lat : " + p.getLatitude() + ", log : " + p.getLongitude());
			txtP3Status.setText(sb.toString());
			sb = new StringBuilder("Win/Lose (%): ");
		case 2:
			p = players.get(1);
			txtP2Id.setText(p.getId());
			sb.append(p.getWin() + " / " + p.getLose() + " (" + (int)p.calculateWinRate()
					+ ")\n");
			sb.append("lat : " + p.getLatitude() + ", log : " + p.getLongitude());
			txtP2Status.setText(sb.toString());
			sb = new StringBuilder("Win/Lose (%): ");
		case 1:
			p = players.get(0);
			txtP1Id.setText(p.getId());
			sb.append(p.getWin() + " / " + p.getLose() + " (" + (int)p.calculateWinRate()
					+ ")\n");
			sb.append("lat : " + p.getLatitude() + ", log : " + p.getLongitude());
			txtP1Status.setText(sb.toString());
			sb = new StringBuilder("Win/Lose (%): ");
		}
		
		txtWindDir.setText("Deg : "+room.getWindDeg());
		txtWindSpd.setText("Speed : "+room.getWindSpeed());
	}
	
	private void clear(){
		txtP3Id.setText("");
		txtP3Status.setText("");
		txtP2Id.setText("");
		txtP2Status.setText("");
		txtP1Id.setText("");
		txtP1Status.setText("");
	}
	
	private onNetworkProcessListener mListener = new onNetworkProcessListener() {
		
		@Override
		public void onPostExecute(String result) {
			AlertDialog dialog = mFactory.create(result);
			
			if(dialog != null){
				dialog.show();
			}
		}
	};

}